#!/usr/bin/env python2.5
# -*- coding: UTF-8 -*-  
#import pickle
  
from google.appengine.ext import db
#from google.appengine.ext import deferred  
#import datetime 
#------------------------------------------------------------------------------------------------------------------------- 
class nmModel(db.Model):  
    @classmethod
    def rpcEventual(cls):return db.create_rpc(read_policy=db.EVENTUAL_CONSISTENCY) 
    @classmethod
    def get_by_key_name_eventual(cls, keyname):return cls.get_by_key_name(keyname,  rpc=cls.rpcEventual()) 
    def getKVdict(self): 
        kvdic=self.properties()
        for k in kvdic.keys():
            kvdic[k]=kvdic[k].get_value_for_datastore(self)
##        return kvdic    
    @classmethod
    def flush_all(cls, batchsize=999):
        q=cls.all()
        q.keys_only=True 
        r=q.fetch(batchsize)
        if len(r) == 0 : return True
        else:
            db.delete(r)
            cls.flush_all(batchsize)
# TODO:remove it we are not using it            
#class DicPropertyPicled(db.Property):
#    data_type = dict 
#    def get_value_for_datastore(self, model_instance):
#        value = super(DicPropertyPicled, self).get_value_for_datastore(model_instance)
#        return db.Blob(pickle.dumps(value)) 
#    def make_value_from_datastore(self, value):
#        if value is None:
#            return dict()
#        return pickle.loads(value) 
#    def default_value(self):
#        if self.default is None:
#            return dict()
#        else:
#          return super(DicPropertyPicled, self).default_value().copy() 
#    def validate(self, value):
#        if not isinstance(value, dict):
#            raise db.BadValueError('Property %s needs to be convertible to a dict instance (%s) of class dict' % (self.name, value))  
#        return super(DicPropertyPicled, self).validate(value) 
#    def empty(self, value):
#        return value is None   
 
class DicPropertyEval(db.Property):
    data_type = dict 
    def get_value_for_datastore(self, model_instance): 
        return db.Text(repr(super(DicPropertyEval, self).get_value_for_datastore(model_instance) ) ) 
    def make_value_from_datastore(self, value):
        if value is None:
            return dict()
        return eval(value) 
    def default_value(self):
        if self.default is None:return dict()
        else:return super(DicPropertyEval, self).default_value().copy() 
    def validate(self, value): 
#        if not isinstance(value, dict):
#            raise db.BadValueError(&#39;Property %s needs to be convertible &#39;
#                                 &#39;to a dict instance (%s) of class dict&#39; % (self.name, value))
        return super(DicPropertyEval, self).validate(value) 
    def empty(self, value):return value is None


def clone_entity(e, **extra_args):
    """Clones an entity, adding or overriding constructor attributes.
    
    The cloned entity will have exactly the same property values as the original
    entity, except where overridden. By default it will have no parent entity or
    key name, unless supplied.
    
    Args:
      e: The entity to clone
      extra_args: Keyword arguments to override from the cloned entity and pass
        to the constructor.
    Returns:
      A cloned, possibly modified, copy of entity e.
    """
    klass = e.__class__
    props = dict((k, v.__get__(e, klass)) for k, v in klass.properties().iteritems())
    props.update(extra_args)
    return klass(**props)


def getJson(item, recursive=True):  
    rtdict={}
    for k in item.properties().keys():
        vl=getattr(item, k) 
        if isinstance(vl, db.Model) and recursive:rtdict[k]=getJson(vl, recursive) 
        elif vl is None: rtdict[k]='null'  
        else:rtdict[k]=repr(vl)     
    return rtdict 
